import * as THREE from 'three';
import xrSubtitleSystem from './subtitles/XRSubtitleSystem.js';
import { ModelLoader, AnimationController } from './ModelLoader.js';
import { getPoetModelConfig } from './config/poet-models-config.js';
import { animationDebugger } from './utils/animation-debugger.js';

export class AICharacter {
    constructor(scene, options = {}) {
        this.scene = scene;
        
        // 获取角色配置
        const poetId = options.poetId || 'liqingzhao'; // 默认使用李清照
        const characterConfig = getPoetModelConfig(poetId);
        
        this.options = {
            modelUrl: options.modelUrl || characterConfig.modelUrl,
            position: options.position || new THREE.Vector3(
                characterConfig.position.x,
                characterConfig.position.y, 
                characterConfig.position.z
            ),
            scale: options.scale || characterConfig.scale,
            name: options.name || characterConfig.name || 'AI角色',
            animations: characterConfig.animations,
            bones: characterConfig.bones,
            materials: characterConfig.materials,
            ...options
        };
        
        this.modelLoader = new ModelLoader();
        this.modelData = null;
        this.animationController = null;
        this.character = null;
        this.isLoaded = false;
        
        // 情绪状态
        this.currentEmotion = 'neutral';
        this.emotionIntensity = 1.0;
        
        // 说话状态
        this.isSpeaking = false;
        this.speechAnimation = null;
        
        // 唇语同步
        this.currentViseme = 'sil';
        this.visemeIntensity = 0;
        this.mouthShapes = this.initializeMouthShapes();
        this.lipSyncEnabled = false;
        this.mouthBones = [];
        this.mouthMeshes = [];
        this.morphTargets = null;
        
        // 眼神跟踪
        this.lookTarget = new THREE.Vector3(0, 1.6, 2);
        this.headBone = null;
        this.eyeBones = [];
        
        this.clock = new THREE.Clock();
        this.init();
    }
    
    /**
     * 初始化嘴部形状映射
     */
    initializeMouthShapes() {
        return {
            // 静音/闭嘴
            'sil': { scaleX: 1.0, scaleY: 0.3, scaleZ: 1.0, offsetY: 0 },
            
            // 元音
            'a': { scaleX: 1.8, scaleY: 1.5, scaleZ: 1.0, offsetY: -0.02 },    // 啊
            'e': { scaleX: 1.4, scaleY: 1.0, scaleZ: 1.0, offsetY: -0.01 },    // 额
            'i': { scaleX: 1.2, scaleY: 0.6, scaleZ: 1.0, offsetY: 0.01 },     // 衣
            'o': { scaleX: 1.0, scaleY: 1.2, scaleZ: 1.0, offsetY: 0 },        // 哦
            'u': { scaleX: 0.8, scaleY: 1.0, scaleZ: 1.2, offsetY: 0.01 },     // 乌
            'v': { scaleX: 1.3, scaleY: 0.8, scaleZ: 1.0, offsetY: 0 },        // 额（轻声）
            
            // 辅音
            'p': { scaleX: 1.0, scaleY: 0.2, scaleZ: 1.0, offsetY: 0 },        // 波、泼、摸
            'b': { scaleX: 1.0, scaleY: 0.2, scaleZ: 1.0, offsetY: 0 },        // 波、泼、摸
            'm': { scaleX: 1.0, scaleY: 0.2, scaleZ: 1.0, offsetY: 0 },        // 摸
            'f': { scaleX: 1.2, scaleY: 0.4, scaleZ: 1.0, offsetY: 0.005 },    // 佛
            'w': { scaleX: 0.8, scaleY: 0.8, scaleZ: 1.2, offsetY: 0.01 },     // 我
            't': { scaleX: 1.1, scaleY: 0.6, scaleZ: 1.0, offsetY: 0 },        // 特
            'd': { scaleX: 1.1, scaleY: 0.6, scaleZ: 1.0, offsetY: 0 },        // 得
            'n': { scaleX: 1.1, scaleY: 0.6, scaleZ: 1.0, offsetY: 0 },        // 呢
            'l': { scaleX: 1.1, scaleY: 0.7, scaleZ: 1.0, offsetY: 0 },        // 勒
            'k': { scaleX: 1.3, scaleY: 0.8, scaleZ: 1.0, offsetY: -0.005 },   // 科
            'g': { scaleX: 1.3, scaleY: 0.8, scaleZ: 1.0, offsetY: -0.005 },   // 哥
            'h': { scaleX: 1.2, scaleY: 0.9, scaleZ: 1.0, offsetY: -0.005 },   // 喝
            'j': { scaleX: 1.1, scaleY: 0.7, scaleZ: 1.0, offsetY: 0 },        // 基
            'q': { scaleX: 1.1, scaleY: 0.7, scaleZ: 1.0, offsetY: 0 },        // 欺
            'x': { scaleX: 1.1, scaleY: 0.7, scaleZ: 1.0, offsetY: 0 },        // 希
            'zh': { scaleX: 1.2, scaleY: 0.8, scaleZ: 1.0, offsetY: 0 },       // 知
            'ch': { scaleX: 1.2, scaleY: 0.8, scaleZ: 1.0, offsetY: 0 },       // 吃
            'sh': { scaleX: 1.2, scaleY: 0.8, scaleZ: 1.0, offsetY: 0 },       // 诗
            'r': { scaleX: 1.1, scaleY: 0.8, scaleZ: 1.0, offsetY: 0 },        // 日
            'z': { scaleX: 1.1, scaleY: 0.7, scaleZ: 1.0, offsetY: 0 },        // 资
            'c': { scaleX: 1.1, scaleY: 0.7, scaleZ: 1.0, offsetY: 0 },        // 雌
            's': { scaleX: 1.1, scaleY: 0.7, scaleZ: 1.0, offsetY: 0 },        // 思
            'y': { scaleX: 1.0, scaleY: 0.8, scaleZ: 1.1, offsetY: 0.005 }     // 衣
        };
    }

    async init() {
        try {
            if (this.options.modelUrl) {
                await this.loadCharacterModel();
            } else {
                await this.createDefaultCharacter();
            }
            this.setupBehaviors();
            this.isLoaded = true;
        } catch (error) {
            console.error('AI角色初始化失败:', error);
            await this.createDefaultCharacter();
            this.isLoaded = true;
        }
    }

    /**
     * 加载角色模型
     */
    async loadCharacterModel() {
        const modelData = await this.modelLoader.loadModel(this.options.modelUrl, {
            scale: this.options.scale,
            position: this.options.position,
            castShadow: true,
            receiveShadow: true
        });

        this.modelData = modelData;
        this.character = modelData.model;
        this.scene.add(this.character);

        // 设置动画控制器
        if (modelData.animations.length > 0) {
            this.animationController = new AnimationController(modelData, this.clock);
            
            // 在开发模式下启用动画调试器
            if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                console.log('启用动画调试器');
                animationDebugger.inspectModel(modelData, this.animationController);
                
                // 输出可用动画列表
                const availableAnimations = this.animationController.getAnimationNames();
                console.log('可用动画:', availableAnimations);
                
                // 检查配置的动画是否存在
                this.validateAnimationConfig();
            }
        }

        // 查找重要的骨骼
        this.findImportantBones();
        
        console.log(`角色模型 "${this.options.name}" 加载完成`);
    }

    /**
     * 创建默认角色（当没有提供模型时）
     */
    async createDefaultCharacter() {
        const group = new THREE.Group();
        group.name = this.options.name;
        
        // 身体
        const bodyGeometry = new THREE.CylinderGeometry(0.4, 0.5, 1.2, 12);
        const bodyMaterial = new THREE.MeshPhongMaterial({ 
            color: 0x4a90e2,
            shininess: 30
        });
        const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
        body.position.y = 0.6;
        body.castShadow = true;
        body.name = 'body';
        group.add(body);
        
        // 头部
        const headGeometry = new THREE.SphereGeometry(0.35, 16, 16);
        const headMaterial = new THREE.MeshPhongMaterial({ 
            color: 0x5ba0f2,
            shininess: 50
        });
        const head = new THREE.Mesh(headGeometry, headMaterial);
        head.position.y = 1.5;
        head.castShadow = true;
        head.name = 'head';
        group.add(head);
        
        // 眼睛
        this.createEyes(group);
        
        // 嘴巴
        this.createMouth(group);
        
        // 手臂
        this.createArms(group);
        
        // 设置位置和缩放
        group.position.copy(this.options.position);
        group.scale.setScalar(this.options.scale);
        
        this.character = group;
        this.scene.add(group);
        
        // 创建简单的动画系统
        this.createDefaultAnimations();
        
        console.log(`默认角色 "${this.options.name}" 创建完成`);
    }

    /**
     * 创建眼睛
     */
    createEyes(parent) {
        const eyeGeometry = new THREE.SphereGeometry(0.06, 12, 12);
        const eyeMaterial = new THREE.MeshPhongMaterial({ 
            color: 0x00ff88,
            emissive: 0x002200
        });
        
        const leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
        leftEye.position.set(-0.12, 1.55, 0.28);
        leftEye.name = 'leftEye';
        parent.add(leftEye);
        
        const rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
        rightEye.position.set(0.12, 1.55, 0.28);
        rightEye.name = 'rightEye';
        parent.add(rightEye);
        
        this.eyeBones = [leftEye, rightEye];
    }

    /**
     * 创建嘴巴
     */
    createMouth(parent) {
        const mouthGeometry = new THREE.RingGeometry(0.03, 0.08, 8);
        const mouthMaterial = new THREE.MeshPhongMaterial({ 
            color: 0x333333,
            side: THREE.DoubleSide
        });
        const mouth = new THREE.Mesh(mouthGeometry, mouthMaterial);
        mouth.position.set(0, 1.35, 0.32);
        mouth.rotation.x = -Math.PI / 2;
        mouth.name = 'mouth';
        parent.add(mouth);
        
        this.mouth = mouth;
    }

    /**
     * 创建手臂
     */
    createArms(parent) {
        const armGeometry = new THREE.CylinderGeometry(0.08, 0.1, 0.8, 8);
        const armMaterial = new THREE.MeshPhongMaterial({ color: 0x4a90e2 });
        
        const leftArm = new THREE.Mesh(armGeometry, armMaterial);
        leftArm.position.set(-0.6, 0.8, 0);
        leftArm.rotation.z = Math.PI / 6;
        leftArm.castShadow = true;
        leftArm.name = 'leftArm';
        parent.add(leftArm);
        
        const rightArm = new THREE.Mesh(armGeometry, armMaterial);
        rightArm.position.set(0.6, 0.8, 0);
        rightArm.rotation.z = -Math.PI / 6;
        rightArm.castShadow = true;
        rightArm.name = 'rightArm';
        parent.add(rightArm);
        
        this.arms = { left: leftArm, right: rightArm };
    }

    /**
     * 验证动画配置
     */
    validateAnimationConfig() {
        if (!this.animationController || !this.options.animations) return;
        
        const availableAnimations = this.animationController.getAnimationNames();
        const configuredAnimations = this.options.animations;
        
        console.log('=== 动画配置验证 ===');
        console.log('配置的动画映射:', configuredAnimations);
        console.log('模型中的实际动画:', availableAnimations);
        
        const missingAnimations = [];
        const validAnimations = [];
        
        for (const [systemName, modelName] of Object.entries(configuredAnimations)) {
            if (availableAnimations.includes(modelName)) {
                validAnimations.push({ systemName, modelName });
                console.log(`✅ ${systemName} -> ${modelName} (存在)`);
            } else {
                missingAnimations.push({ systemName, modelName });
                console.warn(`❌ ${systemName} -> ${modelName} (不存在)`);
            }
        }
        
        if (missingAnimations.length > 0) {
            console.warn('缺失的动画:', missingAnimations);
            console.log('建议更新character-config.js中的动画映射');
        }
        
        console.log('=== 验证完成 ===');
        
        return {
            valid: validAnimations,
            missing: missingAnimations,
            available: availableAnimations
        };
    }

    /**
     * 查找重要的骨骼节点
     */
    findImportantBones() {
        if (!this.character) return;
        
        const boneNames = this.options.bones || {};
        
        this.character.traverse((child) => {
            if (child.isBone || child.type === 'Bone') {
                const name = child.name.toLowerCase();
                
                // 查找头部骨骼
                if (name.includes(boneNames.head?.toLowerCase() || 'head')) {
                    this.headBone = child;
                    console.log('找到头部骨骼:', child.name);
                }
                
                // 查找眼部骨骼
                if (name.includes(boneNames.leftEye?.toLowerCase() || 'lefteye') || 
                    name.includes('eye') && name.includes('l')) {
                    this.eyeBones.push(child);
                    console.log('找到左眼骨骼:', child.name);
                }
                
                if (name.includes(boneNames.rightEye?.toLowerCase() || 'righteye') || 
                    name.includes('eye') && name.includes('r')) {
                    this.eyeBones.push(child);
                    console.log('找到右眼骨骼:', child.name);
                }
                
                // 查找嘴部相关骨骼
                if (name.includes('mouth') || name.includes('jaw') || name.includes('lip') || 
                    name.includes('chin') || name.includes('嘴') || name.includes('下巴')) {
                    this.mouthBones.push(child);
                    console.log('找到嘴部骨骼:', child.name);
                }
            }
            
            // 查找嘴部网格和morph targets
            if (child.isMesh) {
                const name = child.name.toLowerCase();
                
                // 查找可能包含嘴部的网格
                if (name.includes('head') || name.includes('face') || name.includes('mouth') || 
                    name.includes('body') || name.includes('头') || name.includes('脸') || name.includes('嘴')) {
                    
                    // 检查是否有morph targets
                    if (child.morphTargetInfluences && child.morphTargetInfluences.length > 0) {
                        console.log(`找到包含morph targets的网格: ${child.name}`);
                        console.log('Morph targets数量:', child.morphTargetInfluences.length);
                        
                        if (child.morphTargetDictionary) {
                            console.log('Morph target字典:', Object.keys(child.morphTargetDictionary));
                            
                            // 查找嘴部相关的morph targets
                            const mouthMorphs = {};
                            for (const [morphName, index] of Object.entries(child.morphTargetDictionary)) {
                                const lowerName = morphName.toLowerCase();
                                if (lowerName.includes('mouth') || lowerName.includes('lip') || 
                                    lowerName.includes('jaw') || lowerName.includes('smile') ||
                                    lowerName.includes('viseme') || lowerName.includes('phoneme') ||
                                    lowerName.includes('a') || lowerName.includes('e') || 
                                    lowerName.includes('i') || lowerName.includes('o') || 
                                    lowerName.includes('u')) {
                                    mouthMorphs[morphName] = index;
                                    console.log(`找到嘴部morph target: ${morphName} (索引: ${index})`);
                                }
                            }
                            
                            if (Object.keys(mouthMorphs).length > 0) {
                                this.morphTargets = {
                                    mesh: child,
                                    morphs: mouthMorphs
                                };
                            }
                        }
                    }
                    
                    // 添加到嘴部网格列表
                    this.mouthMeshes.push(child);
                }
            }
        });
        
        console.log(`找到 ${this.eyeBones.length} 个眼部骨骼`);
        console.log(`找到 ${this.mouthBones.length} 个嘴部骨骼`);
        console.log(`找到 ${this.mouthMeshes.length} 个可能包含嘴部的网格`);
        if (this.morphTargets) {
            console.log(`找到morph targets支持，包含 ${Object.keys(this.morphTargets.morphs).length} 个嘴部相关变形`);
        }
    }

    /**
     * 创建默认动画
     */
    createDefaultAnimations() {
        this.defaultAnimations = {
            idle: () => this.idleAnimation(),
            happy: () => this.happyAnimation(),
            sad: () => this.sadAnimation(),
            excited: () => this.excitedAnimation(),
            thinking: () => this.thinkingAnimation(),
            greeting: () => this.greetingAnimation(),
            speaking: () => this.speakingAnimation()
        };
    }

    /**
     * 设置行为系统
     */
    setupBehaviors() {
        // 呼吸动画
        this.startBreathingAnimation();
        
        // 眨眼动画
        this.startBlinkingAnimation();
        
        // 空闲时的微动画
        this.startIdleBehavior();
    }

    /**
     * 播放动画
     * @param {string} animationName - 动画名称
     * @param {Object} options - 动画选项
     */
    playAnimation(animationName, options = {}) {
        if (this.animationController && this.animationController.hasAnimation(animationName)) {
            // 使用真实模型的动画
            this.animationController.playAnimation(animationName, options);
        } else if (this.defaultAnimations && this.defaultAnimations[animationName]) {
            // 使用默认动画
            this.defaultAnimations[animationName]();
        } else {
            // 从配置中获取实际的动画名称
            const actualAnimationName = this.options.animations && this.options.animations[animationName] ? this.options.animations[animationName] : animationName;
            
            if (this.animationController && this.animationController.hasAnimation(actualAnimationName)) {
                console.log(`播放动画: ${animationName} -> ${actualAnimationName}`);
                this.animationController.playAnimation(actualAnimationName, {
                    loop: options.loop !== false,
                    crossFade: options.crossFade !== false,
                    crossFadeDuration: options.crossFadeDuration || 0.3,
                    ...options
                });
            } else {
                console.warn(`动画 "${animationName}" 不存在`);
            }
        }
    }

    /**
     * 设置情绪
     * @param {string} emotion - 情绪类型
     * @param {number} intensity - 强度 (0-1)
     */
    setEmotion(emotion, intensity = 1.0) {
        this.currentEmotion = emotion;
        this.emotionIntensity = intensity;
        
        // 根据情绪调整外观
        this.updateEmotionalAppearance();
        
        // 播放对应的情绪动画
        this.playAnimation(emotion);
    }

    /**
     * 更新情绪外观
     */
    updateEmotionalAppearance() {
        if (!this.character) return;
        
        const eyeColor = this.getEmotionColor(this.currentEmotion);
        
        // 更新眼睛颜色
        this.eyeBones.forEach(eye => {
            if (eye.material) {
                eye.material.color.setHex(eyeColor);
                eye.material.emissive.setHex(eyeColor * 0.1);
            }
        });
    }

    /**
     * 获取情绪对应的颜色
     * @param {string} emotion - 情绪类型
     * @returns {number} 颜色值
     */
    getEmotionColor(emotion) {
        const colors = {
            happy: 0x00ff00,
            sad: 0x0066ff,
            excited: 0xff6600,
            angry: 0xff0000,
            thinking: 0xffff00,
            neutral: 0x00ff88,
            surprised: 0xff00ff
        };
        return colors[emotion] || colors.neutral;
    }

    /**
     * 开始说话
     * @param {string} text - 说话内容
     * @param {number} duration - 持续时间（毫秒）
     */
    startSpeaking(text, duration = 3000) {
        this.isSpeaking = true;
        this.playAnimation('speaking');
        
        // 嘴巴动画
        if (this.mouth) {
            this.animateMouth(duration);
        }
        
        setTimeout(() => {
            this.stopSpeaking();
        }, duration);
    }

    /**
     * 停止说话
     */
    stopSpeaking() {
        this.isSpeaking = false;
        this.playAnimation('idle');
    }

    /**
     * 嘴巴动画（兼容旧版本）
     * @param {number} duration - 持续时间
     */
    animateMouth(duration) {
        if (this.lipSyncEnabled) {
            // 如果启用了唇语同步，使用visemes动画
            return;
        }
        
        if (!this.mouth) return;
        
        this.mouth.userData = this.mouth.userData || {};
        this.mouth.userData.mouthAnimation = {
            startTime: Date.now(),
            duration: duration,
            originalScale: this.mouth.scale.clone()
        };
    }
    
    /**
     * 启用唇语同步
     */
    enableLipSync() {
        this.lipSyncEnabled = true;
        console.log('唇语同步已启用');
    }
    
    /**
     * 禁用唇语同步
     */
    disableLipSync() {
        this.lipSyncEnabled = false;
        this.resetMouthShape();
        console.log('唇语同步已禁用');
    }
    
    /**
     * 设置viseme（音素形状）
     * @param {string} viseme - 音素名称
     * @param {number} intensity - 强度 (0-1)
     */
    setViseme(viseme, intensity = 1.0) {
        if (!this.mouth || !this.lipSyncEnabled) return;
        
        const shape = this.mouthShapes[viseme] || this.mouthShapes['sil'];
        this.currentViseme = viseme;
        this.visemeIntensity = intensity;
        
        // 应用形状变换
        this.applyMouthShape(shape, intensity);
    }
    
    /**
     * 应用嘴部形状
     * @param {Object} shape - 形状参数
     * @param {number} intensity - 强度
     */
    applyMouthShape(shape, intensity) {
        // 优先使用morph targets（适用于glTF模型）
        if (this.morphTargets && this.applyMorphTargetShape(shape, intensity)) {
            return;
        }
        
        // 使用骨骼动画（适用于有嘴部骨骼的模型）
        if (this.mouthBones.length > 0 && this.applyBoneShape(shape, intensity)) {
            return;
        }
        
        // 回退到简单几何体变形（适用于默认角色）
        if (this.mouth) {
            this.applyGeometryShape(shape, intensity);
        }
    }
    
    /**
     * 使用morph targets应用嘴部形状
     * @param {Object} shape - 形状参数
     * @param {number} intensity - 强度
     * @returns {boolean} 是否成功应用
     */
    applyMorphTargetShape(shape, intensity) {
        if (!this.morphTargets || !this.morphTargets.mesh) return false;
        
        const { mesh, morphs } = this.morphTargets;
        const viseme = this.currentViseme;
        
        // 重置所有morph targets
        if (mesh.morphTargetInfluences) {
            for (let i = 0; i < mesh.morphTargetInfluences.length; i++) {
                mesh.morphTargetInfluences[i] = 0;
            }
        }
        
        // 查找匹配的morph target
        let targetIndex = -1;
        
        // 直接匹配viseme名称
        if (morphs[viseme] !== undefined) {
            targetIndex = morphs[viseme];
        } else {
            // 尝试匹配相似的名称
            const visemeLower = viseme.toLowerCase();
            for (const [morphName, index] of Object.entries(morphs)) {
                const morphLower = morphName.toLowerCase();
                if (morphLower.includes(visemeLower) || 
                    (visemeLower === 'a' && morphLower.includes('mouth_open')) ||
                    (visemeLower === 'o' && morphLower.includes('mouth_o')) ||
                    (visemeLower === 'u' && morphLower.includes('mouth_u')) ||
                    (visemeLower === 'e' && morphLower.includes('mouth_e')) ||
                    (visemeLower === 'i' && morphLower.includes('mouth_i')) ||
                    (visemeLower === 'sil' && morphLower.includes('mouth_close'))) {
                    targetIndex = index;
                    break;
                }
            }
        }
        
        // 应用morph target
        if (targetIndex >= 0 && mesh.morphTargetInfluences) {
            const targetIntensity = Math.max(0, Math.min(1, intensity));
            mesh.morphTargetInfluences[targetIndex] = targetIntensity;
            return true;
        }
        
        return false;
    }
    
    /**
     * 使用骨骼动画应用嘴部形状
     * @param {Object} shape - 形状参数
     * @param {number} intensity - 强度
     * @returns {boolean} 是否成功应用
     */
    applyBoneShape(shape, intensity) {
        if (this.mouthBones.length === 0) return false;
        
        // 对每个嘴部骨骼应用变形
        this.mouthBones.forEach(bone => {
            if (bone.name.toLowerCase().includes('jaw')) {
                // 下颌骨骼 - 主要控制张嘴
                const openAmount = (shape.scaleY - 1.0) * intensity * 0.3;
                bone.rotation.x = openAmount;
            } else if (bone.name.toLowerCase().includes('lip')) {
                // 嘴唇骨骼 - 控制嘴唇形状
                const lipScale = 1.0 + (shape.scaleX - 1.0) * intensity * 0.2;
                bone.scale.setScalar(lipScale);
            }
        });
        
        return true;
    }
    
    /**
     * 使用几何体变形应用嘴部形状（回退方案）
     * @param {Object} shape - 形状参数
     * @param {number} intensity - 强度
     */
    applyGeometryShape(shape, intensity) {
        // 计算目标缩放
        const targetScale = new THREE.Vector3(
            1.0 + (shape.scaleX - 1.0) * intensity,
            1.0 + (shape.scaleY - 1.0) * intensity,
            1.0 + (shape.scaleZ - 1.0) * intensity
        );
        
        // 平滑过渡到目标形状
        this.mouth.scale.lerp(targetScale, 0.3);
        
        // 应用位置偏移
        if (shape.offsetY) {
            const targetY = 1.35 + shape.offsetY * intensity;
            this.mouth.position.y += (targetY - this.mouth.position.y) * 0.3;
        }
    }
    
    /**
     * 重置嘴部形状
     */
    resetMouthShape() {
        // 重置morph targets
        if (this.morphTargets && this.morphTargets.mesh && this.morphTargets.mesh.morphTargetInfluences) {
            for (let i = 0; i < this.morphTargets.mesh.morphTargetInfluences.length; i++) {
                this.morphTargets.mesh.morphTargetInfluences[i] = 0;
            }
        }
        
        // 重置嘴部骨骼
        this.mouthBones.forEach(bone => {
            bone.rotation.set(0, 0, 0);
            bone.scale.set(1, 1, 1);
        });
        
        // 重置简单几何体嘴部
        if (this.mouth) {
            this.mouth.scale.set(1, 1, 1);
            this.mouth.position.y = 1.35;
        }
        
        this.currentViseme = 'sil';
        this.visemeIntensity = 0;
    }
    
    /**
     * 更新唇语同步数据
     * @param {Object} lipSyncData - 唇语同步数据
     */
    updateLipSync(lipSyncData) {
        if (!this.lipSyncEnabled) return;
        
        const { viseme, intensity } = lipSyncData;
        this.setViseme(viseme, intensity);
    }

    /**
     * 看向目标
     * @param {THREE.Vector3} target - 目标位置
     */
    lookAt(target) {
        this.lookTarget.copy(target);
        
        if (this.headBone) {
            this.headBone.lookAt(target);
        } else if (this.character) {
            // 简单的头部转向
            const head = this.character.getObjectByName('head');
            if (head) {
                const direction = target.clone().sub(head.getWorldPosition(new THREE.Vector3()));
                const angle = Math.atan2(direction.x, direction.z);
                head.rotation.y = THREE.MathUtils.lerp(head.rotation.y, angle * 0.3, 0.1);
            }
        }
    }

    /**
     * 呼吸动画
     */
    startBreathingAnimation() {
        this.breathingAnimation = {
            enabled: true,
            startTime: Date.now()
        };
    }

    /**
     * 眨眼动画
     */
    startBlinkingAnimation() {
        const blink = () => {
            this.eyeBones.forEach(eye => {
                if (eye.scale) {
                    eye.scale.y = 0.1;
                    setTimeout(() => {
                        eye.scale.y = 1;
                    }, 100);
                }
            });
            
            // 随机间隔眨眼
            setTimeout(blink, 2000 + Math.random() * 3000);
        };
        
        setTimeout(blink, 1000);
    }

    /**
     * 空闲行为
     */
    startIdleBehavior() {
        this.idleBehavior = {
            enabled: true,
            startTime: Date.now()
        };
    }

    // 默认动画实现
    idleAnimation() {
        // 空闲动画已在 startIdleBehavior 中实现
    }

    happyAnimation() {
        if (!this.character) return;
        
        this.character.userData.happyAnimation = {
            startTime: Date.now(),
            duration: 1500,
            originalY: this.character.position.y
        };
    }

    sadAnimation() {
        if (!this.character) return;
        
        const head = this.character.getObjectByName('head');
        if (head) {
            const originalRotation = head.rotation.x;
            head.rotation.x = originalRotation - 0.3;
            
            setTimeout(() => {
                head.rotation.x = originalRotation;
            }, 2000);
        }
    }

    excitedAnimation() {
        this.happyAnimation();
        
        // 额外的手臂动作
        if (this.arms) {
            this.arms.left.userData = this.arms.left.userData || {};
            this.arms.right.userData = this.arms.right.userData || {};
            
            this.arms.left.userData.excitedAnimation = {
                startTime: Date.now(),
                duration: 1000,
                originalRotationZ: this.arms.left.rotation.z
            };
            
            this.arms.right.userData.excitedAnimation = {
                startTime: Date.now(),
                duration: 1000,
                originalRotationZ: this.arms.right.rotation.z
            };
        }
    }

    thinkingAnimation() {
        if (!this.character) return;
        
        const head = this.character.getObjectByName('head');
        if (!head) return;
        
        head.userData = head.userData || {};
        head.userData.thinkingAnimation = {
            startTime: Date.now(),
            duration: 2000
        };
    }

    greetingAnimation() {
        if (!this.arms || !this.arms.right) return;
        
        this.arms.right.userData = this.arms.right.userData || {};
        this.arms.right.userData.greetingAnimation = {
            startTime: Date.now(),
            duration: 1500,
            originalRotationZ: this.arms.right.rotation.z
        };
    }

    speakingAnimation() {
        // 说话动画主要通过 startSpeaking 方法实现
        if (this.character) {
            const time = Date.now() * 0.01;
            const head = this.character.getObjectByName('head');
            if (head) {
                head.rotation.x = Math.sin(time) * 0.05;
            }
        }
    }

    /**
     * 更新角色（在渲染循环中调用）
     */
    update() {
        if (this.animationController) {
            this.animationController.update();
        }
        
        this.updateCharacterAnimations();
    }
    
    /**
     * 更新角色动画状态
     */
    updateCharacterAnimations() {
        const currentTime = Date.now();
        
        // 更新呼吸动画
        if (this.breathingAnimation && this.breathingAnimation.enabled && this.character) {
            const time = currentTime * 0.001;
            const breathScale = 1 + Math.sin(time * 1.5) * 0.02;
            this.character.scale.y = this.options.scale * breathScale;
        }
        
        // 更新空闲行为
        if (this.idleBehavior && this.idleBehavior.enabled && !this.isSpeaking && this.character) {
            const time = currentTime * 0.0005;
            const head = this.character.getObjectByName('head');
            if (head) {
                head.rotation.y = Math.sin(time) * 0.05;
                head.rotation.x = Math.cos(time * 0.7) * 0.02;
            }
        }
        
        // 更新角色动画
        if (this.character && this.character.userData.happyAnimation) {
            const anim = this.character.userData.happyAnimation;
            const elapsed = currentTime - anim.startTime;
            const progress = Math.min(elapsed / anim.duration, 1);
            
            if (progress < 1) {
                this.character.position.y = anim.originalY + Math.sin(progress * Math.PI * 4) * 0.1;
                this.character.rotation.y = Math.sin(progress * Math.PI * 8) * 0.1;
            } else {
                this.character.position.y = anim.originalY;
                this.character.rotation.y = 0;
                delete this.character.userData.happyAnimation;
            }
        }
        
        // 更新头部思考动画
        if (this.character) {
            const head = this.character.getObjectByName('head');
            if (head && head.userData.thinkingAnimation) {
                const anim = head.userData.thinkingAnimation;
                const elapsed = currentTime - anim.startTime;
                const progress = Math.min(elapsed / anim.duration, 1);
                
                if (progress < 1) {
                    head.rotation.y = Math.sin(progress * Math.PI * 2) * 0.2;
                    head.rotation.x = Math.cos(progress * Math.PI * 3) * 0.1;
                } else {
                    head.rotation.y = 0;
                    head.rotation.x = 0;
                    delete head.userData.thinkingAnimation;
                }
            }
        }
        
        // 更新手臂动画
        if (this.arms) {
            // 兴奋动画
            if (this.arms.left.userData && this.arms.left.userData.excitedAnimation) {
                const anim = this.arms.left.userData.excitedAnimation;
                const elapsed = currentTime - anim.startTime;
                const progress = Math.min(elapsed / anim.duration, 1);
                
                if (progress < 1) {
                    const angle = Math.sin(progress * Math.PI * 6) * 0.5;
                    this.arms.left.rotation.z = Math.PI / 6 + angle;
                } else {
                    this.arms.left.rotation.z = Math.PI / 6;
                    delete this.arms.left.userData.excitedAnimation;
                }
            }
            
            if (this.arms.right.userData && this.arms.right.userData.excitedAnimation) {
                const anim = this.arms.right.userData.excitedAnimation;
                const elapsed = currentTime - anim.startTime;
                const progress = Math.min(elapsed / anim.duration, 1);
                
                if (progress < 1) {
                    const angle = Math.sin(progress * Math.PI * 6) * 0.5;
                    this.arms.right.rotation.z = -Math.PI / 6 - angle;
                } else {
                    this.arms.right.rotation.z = -Math.PI / 6;
                    delete this.arms.right.userData.excitedAnimation;
                }
            }
            
            // 问候动画
            if (this.arms.right.userData && this.arms.right.userData.greetingAnimation) {
                const anim = this.arms.right.userData.greetingAnimation;
                const elapsed = currentTime - anim.startTime;
                const progress = Math.min(elapsed / anim.duration, 1);
                
                if (progress < 1) {
                    const waveAngle = Math.sin(progress * Math.PI * 8) * 0.3;
                    this.arms.right.rotation.z = anim.originalRotationZ + waveAngle;
                } else {
                    this.arms.right.rotation.z = anim.originalRotationZ;
                    delete this.arms.right.userData.greetingAnimation;
                }
            }
        }
        
        // 更新嘴部动画
        if (this.mouth && this.mouth.userData && this.mouth.userData.mouthAnimation) {
            const anim = this.mouth.userData.mouthAnimation;
            const elapsed = currentTime - anim.startTime;
            const progress = Math.min(elapsed / anim.duration, 1);
            
            if (progress < 1) {
                if (anim.targetScale !== undefined) {
                    // 简单的缩放动画
                    this.mouth.scale.y = anim.startScale + (anim.targetScale - anim.startScale) * progress;
                } else if (anim.originalScale) {
                    // 说话动画
                    const intensity = 0.5 + Math.sin(elapsed * 0.02) * 0.3;
                    this.mouth.scale.setScalar(anim.originalScale.x * (1 + intensity * 0.3));
                }
            } else {
                if (anim.targetScale !== undefined) {
                    this.mouth.scale.y = anim.targetScale;
                } else if (anim.originalScale) {
                    this.mouth.scale.copy(anim.originalScale);
                }
                delete this.mouth.userData.mouthAnimation;
            }
        }
    }

    /**
     * 获取角色位置
     * @returns {THREE.Vector3} 角色位置
     */
    getPosition() {
        return this.character ? this.character.position.clone() : new THREE.Vector3();
    }

    /**
     * 设置角色位置
     * @param {THREE.Vector3} position - 新位置
     */
    setPosition(position) {
        if (this.character) {
            this.character.position.copy(position);
        }
    }

    /**
     * 销毁角色
     */
    dispose() {
        if (this.animationController) {
            this.animationController.dispose();
        }
        
        if (this.character) {
            this.scene.remove(this.character);
        }
        
        this.modelLoader.clearCache();
    }

    /**
     * 根据音频可视化数据更新角色动画
     * @param {Object} audioFeatures - 音频特征数据
     */
    updateAudioVisualization(audioFeatures) {
        if (!this.model || !audioFeatures) return;
        
        // 根据音频能量调整角色动画强度
        const energy = audioFeatures.energy || 0;
        const volume = audioFeatures.volume || 0;
        
        // 调整呼吸动画的强度
        if (this.breathingAnimation) {
            const breathingIntensity = 1 + (energy * 0.5);
            this.model.scale.setScalar(breathingIntensity);
        }
        
        // 根据音频频率调整角色颜色或材质
        if (this.model.material) {
            const bassLevel = audioFeatures.bass || 0;
            const midLevel = audioFeatures.mid || 0;
            const trebleLevel = audioFeatures.treble || 0;
            
            // 可以根据不同频段调整材质属性
            if (this.model.material.emissive) {
                this.model.material.emissive.setRGB(
                    bassLevel / 255 * 0.2,
                    midLevel / 255 * 0.2,
                    trebleLevel / 255 * 0.2
                );
            }
        }
        
        // 根据音量调整角色位置的微小变化
        if (volume > 0.1) {
            const offsetY = Math.sin(Date.now() * 0.01) * volume * 0.1;
            this.model.position.y = this.originalPosition.y + offsetY;
        }
    }

    /**
     * 处理用户输入（语音识别结果）
     * @param {string} text - 用户输入文本
     */
    async handleUserInput(text) {
        console.log(`角色 ${this.options.name} 收到用户输入:`, text);
        
        // 设置角色为思考状态
        this.setThinkingState(true);
        
        try {
            // 调用AI API获取回答
            const response = await this.getAIResponse(text);
            console.log(`角色 ${this.options.name} 的AI回答:`, response);
            
            // 显示AI响应字幕
            xrSubtitleSystem.showText(response);
            
            // 播放回答
            await this.speak(response);
        } catch (error) {
            console.error(`处理用户输入时出错:`, error);
            
            // 播放错误提示
            try {
                await this.speak('抱歉，我现在无法回答您的问题，请稍后再试。');
            } catch (speakError) {
                console.error('播放错误提示失败:', speakError);
            }
        } finally {
            // 恢复角色为正常状态
            this.setThinkingState(false);
        }
    }

    /**
     * 获取AI响应
     * @param {string} text - 用户输入文本
     * @returns {Promise<string>} AI回答文本
     */
    async getAIResponse(text) {
        // 获取VoiceManager实例
        const voiceManager = window.app?.voiceManager;
        
        if (!voiceManager || !voiceManager.sendMessage) {
            console.error('VoiceManager不可用或缺少sendMessage方法');
            return '我暂时无法理解您的问题。';
        }
        
        try {
            // 调用VoiceManager的sendMessage方法获取AI回答
            const response = await voiceManager.sendMessage(text);
            
            // 处理不同格式的响应
            if (typeof response === 'string') {
                return response;
            } else if (response && response.response) {
                return response.response;
            } else if (response && response.text) {
                return response.text;
            } else {
                console.warn('AI响应格式未知:', response);
                return JSON.stringify(response);
            }
        } catch (error) {
            console.error('获取AI响应失败:', error);
            throw error;
        }
    }

    /**
     * 让角色说话
     * @param {string} text - 要说的文本
     */
    async speak(text) {
        console.log(`角色 ${this.options.name} 正在说话:`, text);
        
        // 设置说话状态
        this.isSpeaking = true;
        
        // 触发说话动画
        this.triggerSpeakingAnimation();
        
        // 获取VoiceManager实例
        const voiceManager = window.app?.voiceManager;
        
        if (!voiceManager || !voiceManager.textToSpeechBrowser) {
            console.error('VoiceManager不可用或缺少textToSpeechBrowser方法');
            this.isSpeaking = false;
            return;
        }
        
        try {
            // 使用浏览器TTS播放文本
            await voiceManager.textToSpeechBrowser(text, {
                lang: 'zh-CN',
                rate: 0.9,  // 稍微放慢语速以提高可理解性
                onStart: () => {
                    console.log('TTS开始播放');
                }
            });
        } catch (error) {
            console.error('语音合成失败:', error);
        } finally {
            // 恢复角色状态
            this.isSpeaking = false;
            
            // 结束说话动画
            this.stopSpeakingAnimation();
            
            // 语音合成结束后延迟隐藏字幕
            setTimeout(() => {
                if (window.app?.voiceManager?.isListening) {
                    // 如果语音识别正在进行，保持显示
                } else {
                    xrSubtitleSystem.hide();
                }
            }, 2000);
            
            // 如果在XR模式下，自动恢复语音识别
            if (window.app?.immersiveExperience?.isXRActive) {
                setTimeout(() => {
                    if (voiceManager && !voiceManager.isListening) {
                        voiceManager.startListening();
                    }
                }, 500);
            }
        }
    }

    /**
     * 设置角色为思考状态
     * @param {boolean} isThinking - 是否处于思考状态
     */
    setThinkingState(isThinking) {
        if (isThinking) {
            // 触发思考动画
            this.triggerThinkingAnimation();
        } else {
            // 停止思考动画
            this.stopThinkingAnimation();
        }
    }

    /**
     * 触发思考动画
     */
    triggerThinkingAnimation() {
        console.log(`角色 ${this.options.name} 正在思考...`);
        
        // 为头部添加思考动画
        if (this.character) {
            const head = this.character.getObjectByName('head');
            if (head) {
                head.userData.thinkingAnimation = {
                    startTime: Date.now(),
                    duration: 1000 // 1秒后重置
                };
            }
        }
    }

    /**
     * 停止思考动画
     */
    stopThinkingAnimation() {
        // 清除头部的思考动画
        if (this.character) {
            const head = this.character.getObjectByName('head');
            if (head && head.userData && head.userData.thinkingAnimation) {
                head.rotation.y = 0;
                head.rotation.x = 0;
                delete head.userData.thinkingAnimation;
            }
        }
    }

    /**
     * 触发说话动画
     */
    triggerSpeakingAnimation() {
        console.log(`角色 ${this.options.name} 开始说话动画`);
        
        // 为嘴巴添加说话动画
        if (this.mouth) {
            this.mouth.userData.mouthAnimation = {
                startTime: Date.now(),
                duration: Infinity, // 持续到停止调用
                originalScale: this.mouth.scale.clone()
            };
        }
        
        // 如果有动画控制器，播放说话动画
        if (this.animationController && this.options.animations?.speaking) {
            this.animationController.playAnimation(this.options.animations.speaking, { loop: true });
        }
    }

    /**
     * 停止说话动画
     */
    stopSpeakingAnimation() {
        // 清除嘴巴的说话动画
        if (this.mouth && this.mouth.userData && this.mouth.userData.mouthAnimation) {
            if (this.mouth.userData.mouthAnimation.originalScale) {
                this.mouth.scale.copy(this.mouth.userData.mouthAnimation.originalScale);
            }
            delete this.mouth.userData.mouthAnimation;
        }
        
        // 如果有动画控制器，恢复到空闲动画
        if (this.animationController && this.options.animations?.idle) {
            this.animationController.playAnimation(this.options.animations.idle, { loop: true });
        }
    }
}